from datetime import datetime
from src.database import db


class Selection(db.Model):
    """选课记录模型"""
    __tablename__ = 'selections'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id', ondelete='CASCADE'), nullable=False)

    status = db.Column(db.String(20), default='selected')  # 状态：selected, dropped
    semester = db.Column(db.String(20), nullable=False)  # 学期
    score = db.Column(db.Float, nullable=True)  # 最终成绩
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        # 联合唯一约束：同一学期内，同一个学生不能多次选同一门课
        db.UniqueConstraint('user_id', 'course_id', 'semester', name='uq_user_course_semester'),
    )

    def to_dict(self, include_course=False):
        """将选课记录转换为字典"""
        data = {
            'id': self.id,
            'user_id': self.user_id,
            'course_id': self.course_id,
            'status': self.status,
            'semester': self.semester,
            'score': self.score,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

        if include_course:
            data['course'] = self.course.to_dict()

        return data

    def __repr__(self):
        return f'<Selection {self.user_id} - {self.course_id}>'


class CourseReview(db.Model):
    """课程评价模型"""
    __tablename__ = 'course_reviews'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id', ondelete='CASCADE'), nullable=False)

    rating_type = db.Column(db.String(20), nullable=False)  # 评分类型: teacher, easiness, homework
    rating = db.Column(db.Integer, nullable=False)  # 评分，1-5分
    comment = db.Column(db.Text, nullable=True)  # 评价内容
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        # 联合唯一约束：同一个用户对同一课程的同一类型评分只能有一个
        db.UniqueConstraint('user_id', 'course_id', 'rating_type', name='uq_user_course_rating_type'),
    )

    def to_dict(self, include_user=False):
        """将评价转换为字典"""
        data = {
            'id': self.id,
            'course_id': self.course_id,
            'rating_type': self.rating_type,
            'rating': self.rating,
            'comment': self.comment,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

        if include_user:
            data['user'] = {
                'id': self.user.id,
                'username': self.user.username
            }
        else:
            data['user_id'] = self.user_id

        return data

    def __repr__(self):
        return f'<CourseReview {self.user_id} - {self.course_id} - {self.rating_type}>'
